<?php 

class Contact_IndexController extends Zend_Controller_Action
{
    /**
     * @var Contact_Form_Contatto 
     */
    private $_formContact;
    
    public function init()
    {
        $this->view->formContact = $this->getFormContact();
    }

    public function indexAction()
    {
        $request = $this->getRequest();
        $post = $request->getPost();
        if ($request->isPost() && $this->_formContact->isValid($post)){
            // Prepere and send the mail
            $result = $this->sendContactMailTo('andrea.biggi@gmail.com', 'Bix');
            //inform the view whith the status
            $this->view->messageProcessed = true;
            if ($result) {
                $this->view->sendError = false;
            } else {
                $this->view->sendError = true;
            }
        }
    }
    
    /**
     * Get the contact form
     *
     * @return Contact_Form_Contatto 
     */
    public function getFormContact()
    {
        $this->_formContact = new Contact_Form_Contatto;
        $this->_formContact->setAction('contact');
        $this->_formContact->setMethod('post');
        
        // Popolo il form se l'utente è loggato 
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $data = array();
            $data['name'] = $auth->getIdentity()->userNome;
            $data['email'] = $auth->getIdentity()->userEmail;
            $this->_formContact->populate($data);
        }
        
        return $this->_formContact;
    }
    
    /**
     * Send the contact mail
     * 
     * @param string $to address mail
     * @param string $toName name 
     * @return Zend_Mail 
     */
    public function sendContactMailTo($to, $toName)
    {
        // Get the posted data
        $sender = $this->_formContact->getValue('name');
        $email = $this->_formContact->getValue('email');
        $subject = $this->_formContact->getValue('subject');
        $message = $this->_formContact->getValue('message');
        
        // Load template
        $htmlMessage = $this->view->partial(
                    'templates/default.phtml',
                    $this->_formContact->getValues() // Passa i parametri al template
                );
        
        $mail = new Zend_Mail();
        
        $mail->setSubject($subject);
        // Set the message's from address to the person who submitted the form
        $mail->setFrom($email, $sender);
        // hardcode the recipient
        $mail->addTo($to, $toName);
        //add the html body
        $mail->setBodyHtml($htmlMessage);
        // Alternative body text message
        $mail->setBodyText($message);
        
        return $mail->send();
    }
}

